package com.frank.auth.application.controller;

import com.frank.auth.application.convert.AuthRoleDtoConvert;
import com.frank.auth.application.dto.AuthRoleDto;
import com.frank.auth.domain.bo.AuthRoleBo;
import com.frank.auth.domain.service.RoleDomainService;
import com.frank.common.entity.Result;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2024/2/13
 * @description
 */
@Slf4j
@RestController
@RequestMapping("/role")
public class RoleController {

    private final RoleDomainService roleDomainService;

    public RoleController(RoleDomainService roleDomainService) {
        this.roleDomainService = roleDomainService;
    }

    @PostMapping(consumes = "application/json")
    public Result<Boolean> addRole(@RequestBody AuthRoleDto authRoleDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("RoleController add role, params: {}", authRoleDto);
            }
            Preconditions.checkNotNull(authRoleDto.getRoleName(), "The role name cannot be empty!");
            Preconditions.checkNotNull(authRoleDto.getRoleKey(), "The role key cannot be empty!");
            AuthRoleBo authRoleBo = AuthRoleDtoConvert.INSTANCE.convertDtoToBo(authRoleDto);
            return Result.ok(roleDomainService.addRole(authRoleBo));
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("RoleController add role error, params: {}", authRoleDto, e);
            }
            return Result.fail(e.getMessage());
        }
    }

    @PutMapping(consumes = "application/json")
    public Result<Boolean> updateRole(@RequestBody AuthRoleDto authRoleDto) {
        try {
            if (log.isInfoEnabled()) {
                log.info("RoleController update role, params: {}", authRoleDto);
            }
            Preconditions.checkNotNull(authRoleDto.getId(), "The id cannot be empty!");
            AuthRoleBo authRoleBo = AuthRoleDtoConvert.INSTANCE.convertDtoToBo(authRoleDto);
            return Result.ok(roleDomainService.updateRole(authRoleBo));
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("RoleController update role error, params: {}", authRoleDto, e);
            }
            return Result.fail(e.getMessage());
        }
    }

    @DeleteMapping("/{roleId}")
    public Result<Boolean> deleteRole(@PathVariable Integer roleId) {
        try {
            if (log.isInfoEnabled()) {
                log.info("RoleController delete role, params: {}", roleId);
            }
            return Result.ok(roleDomainService.deleteRole(Long.valueOf(roleId)));
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("RoleController delete role error, params: {}", roleId, e);
            }
            return Result.fail(e.getMessage());
        }
    }
}
